import {createRouter, createWebHashHistory} from 'vue-router'

const routes = [
    {
        path: "/",
        redirect: "/home"
    },
    {
        path: "/home",
        redirect: "/home/category1",
        name: "home",
        meta: {age: 10},
        component: () => import(/*webpackChunkName:'home'*/"@/views/home/home.vue"),
        children: [
            {
                path: "category1",
                component: () => import("@/views/home/category/category1.vue"),
            },
            {
                path: "category2",
                component: () => import("@/views/home/category/category2.vue"),
            },
            {
                path: "category3",
                component: () => import("@/views/home/category/category3.vue"),
            }
        ]
    },
    {
        path: "/login",
        name: "login",
        component: () => import("@/views/login/login.vue")
    },
    {
        path: "/order-for-goods",
        name: "order-for-goods",
        meta: {age: 11},
        component: () => import(/*webpackChunkName:'login'*/"@/views/order-for-goods/order-for-goods.vue")
    },
    {
        path: "/user/:userId",
        name: "user",
        meta: {age: 11},
        component: () => import(/*webpackChunkName:'login'*/"@/views/user/user.vue")
    },
    {
        //404路由 ,当用户访问的路径不存在的时候显示此组件
        path: "/:pathMatch(.*)",
        component: () => import("@/views/NotFound.vue")
    }
]

const router = createRouter({
    history: createWebHashHistory(),
    routes
})

// 全局前置路由守卫 路由跳转前执行
router.beforeEach((to, from, next) => {
    const token = localStorage.getItem("token")
    if (to.path !== "/login") {
     if (token){
         next()
     }else {
         next("/login")
     }
    }else {
        next()
    }
})
// 全局后置路由守卫 路由跳转后执行
router.afterEach((to, from, failure) => {
    console.log("我是全局后置路由守卫，路由跳转后执行")
})

export default router
